import VueRouter from "vue-router";
import Vue from 'vue'
import routes from './routes'
import store from '@/store/'
Vue.use(VueRouter)
//重写push 方法
const originPush=VueRouter.prototype.push
VueRouter.prototype.push=function (loction,resolve,reject){
    if(resolve&&reject){
      originPush.call(this,loction,resolve,reject)
    }else{
      originPush.call(this,loction,()=>{},()=>{})
    }
}

//重写replace方法
const originReplace=VueRouter.prototype.replace
VueRouter.prototype.replace=function(){
  if(resolve&&reject){
    originReplace.call(this,loction,resolve,reject)
  }else{
    originReplace.call(this,loction,()=>{},()=>{})
  }
}
const  router= new VueRouter(routes)
router.beforeEach(async(to,from,next)=>{
  //
    const token= store.state.login.token // 是否已登入
    const name=store.state.login.userInfo.nickName //是否有信息
    //登录后不能去登录页面
    if(token){
      if(to.path.indexOf('/login')!=-1||to.path.indexOf('/login')!=-1){
          next(false)
      }else{
          if(name){
            next()
          }else{
            //登入过但是token过期了
            try{
              await store.dispatch('userInfo')
              next()
            }catch(error){
                await store.dispatch('loginOut')
                next('/login')
            }
          }
      }    
    }else{
      //未登录：不能去交易相关、不能去支付相关【pay】、不能去个人中心
      //未登录去上面这些路由-----登录
      let toPath = to.path;
      if(toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1||toPath.indexOf('/ordercenter')!=-1){
        //把未登录的时候向去而没有去成的信息，存储于地址栏中【路由】
        next('/login?redirect='+toPath);
      }else{
         //去的不是上面这些路由（home|search|shopCart）---放行
         next();
      }
    }
   
})
export default router